<?php
namespace app\company\controller;

use think\Request;

class User extends Base
{
    public function _initialize(){
        parent::_initialize();
    }

    /**
     * 登陆页
     */
    public function login(Request $request){
        if(session("user_com")){
            $this->redirect("index/index");
        }
        return $this->fetch();
    }

    //接收账号密码登入账号
    public function check_login(){
        if(Request::instance()->isPost()){
            $params = input('post.');
            //验证企业
            $where_1  =   [
                "account_code"   =>  trim($params["account_code"]),
                "is_del"   =>  0,
            ];
            $com = M('company')->where($where_1)->find();
            if(empty($com)){
                return $this->ajaxReturn(1,'该企业不存在或被禁用');
            }
            if($com['status'] == 0){
                return $this->ajaxReturn(1,'该企业已关闭');
            }
            $fieldsArr  =   [
                "id,name,avatar,password,role_id,department_id,com_id,job_number,type,role_id",
            ];
            $where['account'] = $params['account'];
            $where['com_id'] = $com['id'];
            $adminUser  =   model("Users")
                ->where($where)
                ->field($fieldsArr)
                ->find();
            if(empty($adminUser)){
                return $this->ajaxReturn(1,'用户和企业不匹配');
            }
            if($adminUser["password"] != md5($params["password"])){
                return $this->ajaxReturn(1,'用户密码不正确');
            }
            if($adminUser['type'] == 2 && !empty($adminUser['role_id'])){
                return $this->ajaxReturn(1,'该用户被冻结');
            }
            $sessionUserInfo = [
                "id"        =>  $adminUser["id"],
                "name"      =>  $adminUser["name"],
                "avatar"    =>  $adminUser["avatar"],
                "role_id"   =>  $adminUser["role_id"],
                "com_id"   =>  $com["id"],
                "department_id"   =>  $adminUser["department_id"],
                "job_number"   =>  $adminUser["job_number"],
            ];
            session("user_com",$sessionUserInfo);
            return $this->ajaxReturn(0,"登入成功", url('Index/index'));
        }
    }

    /**
     * 忘记密码
     */
    public function forget_pas(){
        if(request()->isPost()){
            $param = input();
            if(!isset($param['mobile']) || !trim($param['mobile'])){
                return $this->ajaxReturn(1, '请输入手机号');
            }
            if(!isset($param['password']) || !trim($param['password'])){
                return $this->ajaxReturn(1, '请输入密码');
            }
            if($param['password'] != $param['password_2']){
                return $this->ajaxReturn(1, '重复密码不一致');
            }
            //检查手机验证码并根据$param中的手机号和接受验证码的手机号对比是否否一致 一致则检查该手机管理用户是否存在
            //***********************************
            $u_info = db('admin_users')->where('mobile', $param['mobile'])->find();
            if(!$u_info){
                return $this->ajaxReturn(1, '该手机账号不存在');
            }
            db('admin_users')->where(['mobile'=>$param['mobile']])->update([
                'password'=>md5($param['password']),
                'password_original'=>$param['password']
            ]);
            return $this->ajaxReturn(0,"修改成功", url('Index/index'));
        }else{
            return $this->fetch();
        }
    }

    //退出
    public function login_out(){
        session("user_com",null);
        $this->redirect("User/login");
    }

    //管理员列表
    public function index(){
        $where = ['com_id'=>$this->com_id];
        $where['type'] = 1;
        if($status = input("get.status/d",0)){
            $where["status"] = $status;
        }
        if($search = trim(input("get.name"))){
            $where["name"] = ["like","%{$search}%"];
        }
        if($s_time = input("get.s_time")){
            $where["c_time"][] = ["egt",strtotime($s_time)];
        }
        if($e_time = input("get.e_time")){
            $where["c_time"][] = ["elt",strtotime($e_time)];
        }
        isset($where["c_time"])&&count($where["c_time"])==1&&$where["c_time"]=$where["c_time"][0];
        $order= str_replace(","," ",input("get._sort","id,asc"));
        $list = model("Users")
            ->where($where)
            ->order($order)
            ->paginate('',false,page_param());
        $this->assign(compact("list"));
        $this->assign("hasTimepicker",1);
        $this->assign("timepickerFormat","YYYY-MM-DD");
        return $this->fetch();
    }

    public function create(Request $request){
        if($request->isPost()){
            return $this->store($request);
        }
        $list = model("Roles")->select();
        $this->assign(compact("list"));
        return $this->fetch();
    }
    //用户设置
    public function user_set(Request $request){

        if($request->isPost()){
            return $this->set_store($request);
        }
        $id = $this->user_id;
        $info = model("Users")->get($id);
        $list = model("Roles")->select();
        $this->assign(compact("info","list"));
        return $this->fetch();
    }
    //用户设置提交
    public function set_store(){
        $params = [];
        $params["name"] = I('name','');
        $params["mobile"] = I('mobile','');
        $params["avatar"] = I('avatar/a',[''])[0];
        if(empty($params['mobile'])){
            return $this->ajaxReturn(1,'手机号码不能为空');
        }
        $params["id"]   =   I("post.id/d",0);

        //验证手机的唯一性
        $where = [];
        $where['id'] = ['neq',$params['id']];
        $where['mobile'] = $params['mobile'];
        $mobile_true = M('users')->where($where)->find();
        if(!empty($mobile_true)){
            return $this->ajaxReturn(1,'该手机号已存在');
        }
        M('users')->where('id',$params['id'])->update($params);
        return $this->ajaxReturn(0,"提交成功");
    }
    //修改密码
    public function update_pass(Request $request){

        if($request->isPost()){
            return $this->pass_store($request);
        }
        return $this->fetch();
    }
    //修改密码提交
    public function pass_store(){
        $params = [];
        $params["old_pass"] = I('old_pass','');
        $params["new_pass"] = I('new_pass','');
        $params["re_pass"] = I('re_pass','');
        if(empty($params['old_pass'])){
            return $this->ajaxReturn(1,'密码不能为空');
        }
        if(empty($params['new_pass'])){
            return $this->ajaxReturn(1,'新密码不能为空');
        }
        if(empty($params['re_pass'])){
            return $this->ajaxReturn(1,'重复密码不能为空');
        }
        if($params['re_pass'] != $params['new_pass']){
            return $this->ajaxReturn(1,'新密码和重复密码不一致');
        }
        $id = $this->user_id;
        //验证用户密码
        $where = [];
        $where['id'] = $id;
        $password = md5($params['old_pass']);
        $users = M('users')->where($where)->find();
        if($users['password'] != $password){
            return $this->ajaxReturn(1,'密码错误');
        }
        M('users')->where('id',$id)->update(['password'=>md5($params['new_pass'])]);
        return $this->ajaxReturn(0,"修改成功");
    }

    private function store(){

        $params = [
            "account"   =>  input("post.account"),
            "password_original" =>  input("post.password_original"),
            "name"      =>  input("post.name"),
            "role_id"   =>  input("post.role_id/d"),
            "status"    =>  input("post.status",'off'),
        ];
        $params = array_filter($params);
        $params["id"]   =   input("post.id/d",0);
        $params["status"]   =   $params["status"]=='on' ? 1 : 2;
        $params["avatar"]   =   isset($_POST["avatar"][0]) ? $_POST["avatar"][0] : "";
        if(isset($params["password_original"])) {
            $params["password"] = md5($params["password_original"]);
            $params["c_time"] = time();
            $params["com_id"] = $this->com_id;
        }
        $userValidate   =   model("User","validate");
        $scene  =   $params["id"] ? 'edit' : 'create';
        if(!$userValidate->scene($scene)->check($params)){
            return $this->ajaxReturn(1,$userValidate->getError());
        }
        //验证账号的唯一性
        if(isset($params["account"])){
            $user = model("Users")->where("account",$params["account"])->find();
            if(empty($params['id']) && $user != null){
                return $this->ajaxReturn(1,"该账号已存在");
            }
        }
        $obj = model("Users");
        if($params["id"]){
            $obj->isUpdate(true)->save($params);
        }else{
            //查询企业最大人数
            $count = M('company')->where('id',$this->com_id)->value('use_people');
            //查询用户数量(不包含冻结用户)
            $where_users = [];
            $where_users['com_id'] = $this->com_id;
            $where_users['type'] = 1;
            $user_count = M('users')->where($where_users)->count();
            if($user_count >= $count){
                return $this->ajaxReturn(1,'超过企业人员数量限制请联系管理员');
            }
            $obj->save($params);
        }

        return $this->ajaxReturn(0,"添加成功", url(CONTROLLER_NAME.'/index'));
    }

    public function edit(Request $request){
        if($request->isPost()){
            return $this->store($request);
        }
        $params =   [
            "id"    =>  input("route.id/d",0),
        ];
        $info = model("Users")->get($params["id"]);
        $list = model("Roles")->where('com_id',$this->com_id)->select();
        $this->assign(compact("info","list"));
        return $this->fetch("create");
    }

    public function delete(){
        $params =   [
            "id"    =>  input("post.id/d",0)
        ];
        $info = model("Users")->where("id",$params["id"])->find();
        if(!$info['role_id']){
            return $this->ajaxReturn(1, "管理员不能删除");
        }
        model("Users")->where("id",$params["id"])->delete();
        return $this->ajaxReturn();
    }
    //权限用户列表
    public function role_user_list(){
        $where = ['com_id'=>$this->com_id];
        if($status = input("get.status/d",0)){
            $where["status"] = $status;
        }
        if($search = trim(input("get.search"))){
            $where["name"] = ["like","%{$search}%"];
        }
        if($s_time = input("get.s_time")){
            $where["c_time"][] = ["egt",strtotime($s_time)];
        }
        if($e_time = input("get.e_time")){
            $where["c_time"][] = ["elt",strtotime($e_time)];
        }
        //权限id
        $id = I('id',0);
        if(empty($id)){
           return $this->error('权限id不能为空');
        }
        $where['role_id'] = $id;
        isset($where["c_time"])&&count($where["c_time"])==1&&$where["c_time"]=$where["c_time"][0];
        $order= str_replace(","," ",input("get._sort","id,asc"));
        $list = model("Users")
            ->where($where)
            ->order($order)
            ->paginate('',false,page_param());
        $this->assign(compact("list"));
        $this->assign("hasTimepicker",1);
        $this->assign("timepickerFormat","YYYY-MM-DD");
        return $this->fetch();
    }
    //删除用户权限
    public function delete_role_user(){
        $id = I('id',0);
        if(empty($id)){
            return $this->error('用户id不能为空');
        }
        M('users')->where('id',$id)->update(['role_id'=>1]);
        return $this->ajaxReturn(0,'删除成功');
    }
    //新增用户权限
    public function add_role_user(Request $request){
        $id = I('role_id',0);
        if(empty($id)){
            return $this->error('角色id不能为空');
        }
        $where = [];
        $where['role_id'] = ['neq',$id];
        $where['com_id'] = $this->com_id;
        $users = M('users')->where($where)->field('id,name')->select();
        $this->assign('users',$users);
        $this->assign('role_id',$id);
        return $this->fetch();
    }
    public function add_role_store(){
        $role_id = I('id',0);
        $user_id = I('user_id/a',[]);
        if(empty($role_id)){
            return $this->ajaxReturn(1,'角色id不能为空');
        }
        if(empty($user_id)){
            return $this->ajaxReturn(1,'用户id不能为空');
        }
        M('users')->where('id','in',$user_id)->update(['role_id'=>$role_id]);
        return $this->ajaxReturn(0,'添加成功');
    }
}
